package com.niu1078.joe.app;

import com.joanzapata.iconify.IconFontDescriptor;
import com.joanzapata.iconify.Iconify;

import java.util.ArrayList;
import java.util.HashMap;

import okhttp3.Interceptor;

/**
 * author :ywq .
 * time: 2017/12/18:17:34.
 * desc :管理各种配置项
 * action:配置文件的存储以及获取
 */

public class Configurator {
    //静态的final 管理配置的存储
    private static final HashMap<Object, Object> JOE_CONFIGS = new HashMap<>();
    //存储字体图标库
    private static final ArrayList<IconFontDescriptor> ICONS = new ArrayList<>();

    //拦截器
    private static  final  ArrayList<Interceptor> INTERCEPTORS = new ArrayList<>();
    private Configurator() {
        //开始配置 但是没有完成
        JOE_CONFIGS.put(ConfigKeys.CONFIG_READY, false);
    }

    /**
     * 安全的懒汉式 单例模式
     */
    private static class Holder {
        private static final Configurator INSTANCE = new Configurator();
    }

    //获取当前类对象
    public static Configurator getInstance() {
        return Holder.INSTANCE;
    }

    //获取配置集合
    final HashMap<Object, Object> getJoeConfigs() {
        return JOE_CONFIGS;
    }

    //配置完成是调用 初始化配置的最后一行调用这个
    public final void configure() {
        initIcons();
        JOE_CONFIGS.put(ConfigKeys.CONFIG_READY, true);
    }

    /**
     * 开始初始化配置
     */

/*
1.配置api host
 */
    public final Configurator withApiHost(String host) {
        JOE_CONFIGS.put(ConfigKeys.API_HOST, host);
        return this;
    }

    /*
2.初始化图标
     */
    private void initIcons() {
        if (ICONS.size() > 0) {
            final Iconify.IconifyInitializer initializer = Iconify.with(ICONS.get(0));
            for (int i = 1; i < ICONS.size(); i++) {
                initializer.with(ICONS.get(i));
            }
        }
    }

    /*
      配置图标
     */
    public final Configurator withIcon(IconFontDescriptor descriptor) {
        ICONS.add(descriptor);
        return this;
    }

    /*
    配置拦截器
     */
    public final Configurator withInterceptor(Interceptor interceptor){

        INTERCEPTORS.add(interceptor);
        JOE_CONFIGS.put(ConfigKeys.INTERCEPTOR,INTERCEPTORS);
        return this;
    }
    public final Configurator withInterceptors(ArrayList<Interceptor> interceptors){

        INTERCEPTORS.addAll(interceptors);
        JOE_CONFIGS.put(ConfigKeys.INTERCEPTOR,INTERCEPTORS);
        return this;
    }
    /**
     * 检查配置项是否完成
     */
    private void checkConfiguration() {
        final boolean isReady = (boolean) JOE_CONFIGS.get(ConfigKeys.CONFIG_READY);

        if (!isReady) {
            throw new RuntimeException("配置项初始化未完成");
        }
    }


    /**
     * 获取配置
     */
    @SuppressWarnings("unchecked")
    final <T> T getConfiguration(Object key) {
        checkConfiguration();
        final Object value = JOE_CONFIGS.get(key);
        if (value == null) {
            throw new NullPointerException(key.toString() + " IS NULL");
        }
        return (T) JOE_CONFIGS.get(key);
    }
}
